package sensor

import (
	"fmt"
	"log"
	"time"
)

// CO2Parser CO2传感器解析器
type CO2Parser struct {
	expectedLength int
}

func NewCO2Parser(dataLength int) *CO2Parser {
	return &CO2Parser{
		expectedLength: dataLength, // 应该是6字节
	}
}

func (p *CO2Parser) Validate(data []byte) bool {
	if len(data) != p.expectedLength {
		log.Printf("CO2数据长度错误: 期望%d字节, 实际%d字节", p.expectedLength, len(data))
		return false
	}
	
	// 检查模块地址是否为0x2C
	if data[0] != 0x2C {
		log.Printf("CO2模块地址错误: 期望0x2C, 实际0x%X", data[0])
		return false
	}
	
	// 计算校验和: B1+B2+B3+B4+B5 取低8位
	calculatedChecksum := byte(0)
	for i := 0; i < 5; i++ { // B1到B5
		calculatedChecksum += data[i]
	}
	
	actualChecksum := data[5] // B6是校验和
	
	if calculatedChecksum != actualChecksum {
		log.Printf("CO2校验和错误: 计算值0x%X, 实际值0x%X", calculatedChecksum, actualChecksum)
		log.Printf("详细计算: 字节[0-4]和=0x%X", calculatedChecksum)
		return false
	}
	
	//log.Printf("CO2校验和正确: 0x%X", calculatedChecksum)
	return true
}

func (p *CO2Parser) Parse(data []byte) (*SensorData, error) {
	if !p.Validate(data) {
		return nil, fmt.Errorf("invalid CO2 data format")
	}

	// 解析CO2浓度值: B2 * 256 + B3
	co2High := uint16(data[1])
	co2Low := uint16(data[2])
	co2Value := co2High*256 + co2Low
	
	// 解析满量程值: B4 * 256 + B5
	fullScaleHigh := uint16(data[3])
	fullScaleLow := uint16(data[4])
	fullScaleValue := fullScaleHigh*256 + fullScaleLow
	
	//log.Printf("CO2传感器解析结果: 浓度=%d ppm, 满量程=%d ppm", co2Value, fullScaleValue)
	
	return &SensorData{
		SensorType: "co2",
		Values: map[string]interface{}{
			"concentration":     co2Value,
			"full_scale":        fullScaleValue,
			"concentration_high": data[1],
			"concentration_low":  data[2],
			"full_scale_high":   data[3],
			"full_scale_low":    data[4],
		},
		RawData:   fmt.Sprintf("%X", data),
		Timestamp: time.Now(),
	}, nil
}